package com.fraud.fm;

import java.io.FileOutputStream;
import java.io.InputStream;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;

import org.apache.log4j.Logger;

import com.fraud.Util;
import com.fraud.model.entity.Sube;

public class WindowsFileManager implements FileManagerIntf {

	private final Logger logger = Logger.getLogger(WindowsFileManager.class);

	public void copyFiles(Sube sube, String fileName) throws Exception {
		try {
			String user = sube.getUserName() + ":" + sube.getPass();

			NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
					user);
			String path = sube.getUrl();

			SmbFile dir = new SmbFile(path, auth);
			int len;
			for (int i = 0; i < dir.listFiles().length; i++) {
				SmbFile s = dir.listFiles()[i];

				FileOutputStream fileOutputStream = new FileOutputStream(
						Util.getProp("waitingFilesPath") + "W_" + sube.getId()
								+ "_" + s.getName());
				InputStream fileInputStream = s.getInputStream();
				byte[] buf = new byte[16 * 1024 * 1024];
				while ((len = fileInputStream.read(buf)) > 0) {
					fileOutputStream.write(buf, 0, len);
				}
				fileInputStream.close();
				fileOutputStream.close();

			}

		} catch (Exception e) {
			logger.error("While copy file Sube:" + sube.getId() + "-"
					+ e.getMessage());
			throw e;
		}
	}
}
